package com.vr.xxaiagent.chatmemory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vr.xxaiagent.chatmemory.converter.MessageConverter;
import com.vr.xxaiagent.model.entity.ChatMessage;
import com.vr.xxaiagent.service.IChatMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 基于Mysql的持久化记忆
 *
 * @author hzh
 * @date 2025/06/01
 */
@Component
@RequiredArgsConstructor
public class MySqlBaseChatMemory implements ChatMemory {
    private final IChatMessageService chatMessageService;


    @Override
    public void add(String conversationId, List<Message> messages) {
        // 转换成 ChatMessage
        List<ChatMessage> chatMessageList = messages.stream()
                .map(message -> MessageConverter.toChatMessage(message, conversationId))
                .toList();
        // 批量保存
        chatMessageService.saveBatch(chatMessageList, chatMessageList.size());
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        // 获取最新的n条消息，就是按照创建时间 降序排序，取前n个
        List<ChatMessage> chatMessageList = chatMessageService.lambdaQuery()
                .eq(ChatMessage::getConversationId, conversationId)
                .orderByDesc(ChatMessage::getCreateTime)
                .last(lastN > 0, "limit " + lastN)
                .list();
        // 输出时按照原来的顺序，就是升序排序，消息越新越靠后
        // 翻转
        if (!chatMessageList.isEmpty()) {
            chatMessageList = chatMessageList.reversed();
        }
        return chatMessageList.stream()
                .map(MessageConverter::toMessage)
                .toList();
    }

    @Override
    public void clear(String conversationId) {
        boolean remove = chatMessageService.remove(new LambdaQueryWrapper<ChatMessage>()
                .eq(ChatMessage::getConversationId, conversationId));
    }
}
